<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 返回按钮 -->
      <div class="mb-6">
        <button 
          class="group flex items-center gap-2 px-4 py-2 bg-white/80 backdrop-blur-sm border border-gray-200 rounded-xl hover:border-indigo-500 hover:text-indigo-500 transition-all duration-300 font-medium shadow-sm hover:shadow-lg"
          @click="goBack"
        >
          <svg class="w-4 h-4 transition-transform duration-300 group-hover:-translate-x-1" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
          </svg>
          返回论坛
        </button>
      </div>

      <ForumLoadingState v-if="loading" message="正在加载帖子内容..." />

      <ForumEmptyState v-else-if="!post" title="帖子不存在" description="抱歉，您访问的帖子不存在或已被删除。" action-text="返回论坛"
        @action="goBack" />

      <div v-else class="space-y-8">
        <!-- 帖子内容 -->
        <ForumPostContent :post="post" :is-liked="isLiked" :can-edit="!!canEdit" @toggle-like="toggleLike"
          @share="sharePost" @edit="editPost" @delete="deletePost" />

        <!-- 回复区域 -->
        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-white/50 overflow-hidden">
          <ForumCommentList :comments="comments" :comments-loading="commentsLoading" :reply-count="post.replyCount"
            :is-locked="!!post.isLocked" :submitting="submitting" :reply-submitting="replySubmitting"
            @submit-comment="submitComment" @toggle-comment-like="toggleCommentLike" @edit-reply="editReply"
            @delete-reply="deleteReply" @submit-reply="submitReply" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Post, Comment } from '~/types/post'
import { postApi, likeApi, commentApi } from '~/utils/api'

// 添加认证中间件
definePageMeta({
  middleware: 'auth'
})

// 获取路由参数
const route = useRoute()
const postId = parseInt(route.params.id as string)

// 响应式数据
const post = ref<Post | null>(null)
const loading = ref(true)
const isLiked = ref(false)
const submitting = ref(false)
const comments = ref<Comment[]>([])
const commentsLoading = ref(false)
const commentsPage = ref(1)
const commentsPageSize = ref(10)
const commentsTotal = ref(0)
const replySubmitting = ref(false)

// 计算属性
const canEdit = computed(() => {
  if (!post.value) return false
  const userStore = useUserStore()
  return post.value.authorId === userStore.user?.id || (userStore.user?.authority && userStore.user.authority >= 2)
})

// 方法
const loadPost = async () => {
  try {
    loading.value = true
    const response = await postApi.getPostByIdApi(postId)

    if (response.success) {
      post.value = response.data
      isLiked.value = response.data.isLiked || false
      // 设置页面标题
      useHead({
        title: post.value.title
      })
      // 加载评论
      await loadComments()
    }
  } catch (error) {
    console.error('加载帖子失败:', error)
  } finally {
    loading.value = false
  }
}

const loadComments = async () => {
  if (!post.value) return

  try {
    commentsLoading.value = true
    const response = await commentApi.getCommentsApi({
      postId: post.value.id,
      page: commentsPage.value,
      pageSize: commentsPageSize.value
    })

    if (response.success) {
      comments.value = response.data.comments
      commentsTotal.value = response.data.total
    }
  } catch (error) {
    console.error('加载评论失败:', error)
  } finally {
    commentsLoading.value = false
  }
}

const toggleLike = async () => {
  if (!post.value) return

  try {
    const response = await likeApi.toggleLikeApi({
      targetType: 'post',
      targetId: post.value.id
    })

    if (response.success) {
      isLiked.value = response.data.liked
      post.value.likeCount = response.data.likeCount
    }
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

const sharePost = async () => {
  if (!post.value) return

  try {
    if (navigator.share) {
      await navigator.share({
        title: post.value.title,
        text: post.value.content.replace(/<[^>]*>/g, '').substring(0, 100),
        url: window.location.href
      })
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(window.location.href)
      console.log('链接已复制到剪贴板')
    }
  } catch (error) {
    console.error('分享失败:', error)
  }
}

const editPost = () => {
  navigateTo(`/StudyArea/Forum/Edit/${postId}`)
}

const deletePost = async () => {
  if (!post.value) return

  const confirmed = confirm('确定要删除这个帖子吗？此操作不可撤销。')

  if (confirmed) {
    try {
      await postApi.deletePostApi(postId)
      console.log('帖子删除成功')
      navigateTo('/StudyArea/Forum')
    } catch (error) {
      console.error('删除帖子失败:', error)
    }
  }
}

const submitComment = async (content: string) => {
  if (!content.trim() || submitting.value || !post.value) return

  try {
    submitting.value = true
    const response = await commentApi.createCommentApi({
      content: content.trim(),
      postId: post.value.id
    })

    if (response.success) {
      console.log('评论发表成功')
      // 重新加载评论列表
      await loadComments()
      // 更新帖子的评论数量
      if (post.value) {
        post.value.replyCount += 1
      }
    }
  } catch (error) {
    console.error('发表评论失败:', error)
  } finally {
    submitting.value = false
  }
}

const submitReply = async (content: string, parentId: number) => {
  if (!content.trim() || replySubmitting.value || !post.value) return

  try {
    replySubmitting.value = true
    const response = await commentApi.createCommentApi({
      content: content.trim(),
      postId: post.value.id,
      parentId: parentId
    })

    if (response.success) {
      console.log('回复发表成功')
      // 重新加载评论列表
      await loadComments()
      // 更新帖子的评论数量
      if (post.value) {
        post.value.replyCount += 1
      }
    }
  } catch (error) {
    console.error('发表回复失败:', error)
  } finally {
    replySubmitting.value = false
  }
}

const editReply = (reply: Comment) => {
  // 实现编辑回复功能
  console.log('编辑回复:', reply)
}

const toggleCommentLike = async (comment: Comment) => {
  try {
    const response = await likeApi.toggleLikeApi({
      targetType: 'comment',
      targetId: comment.id
    })

    if (response.success) {
      comment.isLiked = response.data.liked
      comment.likeCount = response.data.likeCount
    }
  } catch (error) {
    console.error('评论点赞失败:', error)
  }
}

const deleteReply = async (commentId: number) => {
  const confirmed = confirm('确定要删除这条评论吗？')

  if (confirmed) {
    try {
      const response = await commentApi.deleteCommentApi(commentId)

      if (response.success) {
        console.log('评论删除成功')
        // 重新加载评论列表
        await loadComments()
        // 更新帖子的评论数量
        if (post.value) {
          post.value.replyCount -= 1
        }
      }
    } catch (error) {
      console.error('删除评论失败:', error)
    }
  }
}

const goBack = () => {
  navigateTo('/StudyArea/Forum')
}

// 生命周期
onMounted(() => {
  loadPost()
})
</script>
